<template>
  <div class="promotion-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>促销活动管理</span>
          <el-button type="primary" @click="handleAdd">新增促销活动</el-button>
        </div>
      </template>
      <el-table :data="promotionList" style="width: 100%">
        <el-table-column prop="name" label="活动名称" />
        <el-table-column prop="discount" label="折扣力度" />
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="bookCount" label="参与书籍数量" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑促销活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增促销活动' : '编辑促销活动'"
      width="50%"
    >
      <el-form :model="promotionForm" label-width="120px">
        <el-form-item label="活动名称">
          <el-input v-model="promotionForm.name" />
        </el-form-item>
        <el-form-item label="折扣力度">
          <el-input-number v-model="promotionForm.discount" :min="0" :max="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="promotionForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="参与书籍">
          <el-button type="primary" @click="showBookSelector">选择书籍</el-button>
          <div class="selected-books">
            <el-tag
              v-for="book in selectedBooks"
              :key="book._id"
              closable
              @close="removeBook(book)"
            >
              {{ book.name }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 书籍选择器对话框 -->
    <el-dialog
      v-model="bookSelectorVisible"
      title="选择参与促销的书籍"
      width="70%"
    >
      <el-table
        ref="bookTable"
        :data="bookList"
        @selection-change="handleSelectionChange"
        :row-key="row => row._id"
        :selectable="row => row.is_discount !== true"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片" width="80">
          <template #default="scope">
            <el-image
              v-if="scope.row.imgUrl"
              :src="scope.row.imgUrl"
              style="width: 40px; height: 60px"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="书名">
          <template #default="scope">
            {{ scope.row.name }}
            <el-tag v-if="scope.row.is_discount" type="danger" size="small" style="margin-left: 4px;">促销中</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="stock" label="库存" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bookSelectorVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBookSelection">确定</el-button>
        </span>
      </template>
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="bookTotal"
        layout="total, prev, pager, next, jumper"
        @current-change="handleBookPageChange"
        @size-change="handleBookSizeChange"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import app from '@/cloudbase' // 你需要在 src 下新建 cloudbase.js 并配置好环境ID

const promotionList = ref([])
const dialogVisible = ref(false)
const bookSelectorVisible = ref(false)
const dialogType = ref('add')
const promotionForm = ref({
  name: '',
  discount: 0.8,
  timeRange: [],
  bookIds: []
})
const selectedBooks = ref([])
const bookList = ref([])
const selectedBookIds = ref([])
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})
const bookTotal = ref(0)
const bookTable = ref(null)

// 获取促销活动列表
const getPromotionList = async () => {
  try {
    const res = await app.callFunction({
      name: 'promotion',
      data: {
        action: 'getPromotionList'
      }
    })
    if (res.result && res.result.success) {
      promotionList.value = (res.result.data || []).map(item => ({
        ...item,
        bookCount: item.bookIds ? item.bookIds.length : 0
      }))
    } else {
      ElMessage.error('获取促销活动列表失败')
    }
  } catch (error) {
    ElMessage.error('获取促销活动列表失败')
  }
}

// 获取书籍列表
const getBookList = async (page = 1, pageSize = 10) => {
  try {
    const res = await app.callFunction({
      name: 'promotion',
      data: {
        action: 'getBookList',
        pageNum: page,
        pageSize: pageSize
      }
    })
    if (res.result && res.result.success && res.result.data && Array.isArray(res.result.data.list)) {
      bookList.value = res.result.data.list
      bookTotal.value = res.result.data.total
    } else {
      bookList.value = []
      bookTotal.value = 0
    }
  } catch (error) {
    bookList.value = []
    bookTotal.value = 0
    ElMessage.error('获取书籍列表失败')
  }
}

// 新增促销活动
const handleAdd = () => {
  dialogType.value = 'add'
  promotionForm.value = {
    name: '',
    discount: 0.8,
    timeRange: [],
    bookIds: []
  }
  selectedBooks.value = []
  dialogVisible.value = true
}

// 编辑促销活动
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  promotionForm.value = { ...row, timeRange: [row.startTime, row.endTime] }
  // 查询已选书籍详情
  if (row.bookIds && row.bookIds.length > 0) {
    try {
      const res = await app.callFunction({
        name: 'promotion',
        data: {
          action: 'getBooksByIds',
          data: { bookIds: row.bookIds }
        }
      })
      if (res.result && res.result.success) {
        selectedBooks.value = res.result.data
      } else {
        selectedBooks.value = []
      }
    } catch (e) {
      selectedBooks.value = []
    }
  } else {
    selectedBooks.value = []
  }
  dialogVisible.value = true
}

// 删除促销活动
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该促销活动吗？', '提示', {
      type: 'warning'
    })
    await app.callFunction({
      name: 'promotion',
      data: {
        action: 'deletePromotion',
        data: { _id: row._id }
      }
    })
    ElMessage.success('删除成功')
    getPromotionList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 显示书籍选择器
const showBookSelector = () => {
  bookSelectorVisible.value = true
  pagination.currentPage = 1
  getBookList(pagination.currentPage, pagination.pageSize)
}

// 处理书籍选择
const handleSelectionChange = (selection) => {
  // 合并去重所有已选 id
  const ids = new Set(selectedBookIds.value)
  selection.forEach(book => ids.add(book._id))
  // 只保留当前页未被取消的
  bookList.value.forEach(book => {
    if (!selection.find(sel => sel._id === book._id)) {
      ids.delete(book._id)
    }
  })
  selectedBookIds.value = Array.from(ids)
}

// 确认选择书籍
const confirmBookSelection = () => {
  // 跨页：所有已选 id 对应的书籍
  const allBooks = [...(bookList.value || []), ...(selectedBooks.value || [])]
  const map = new Map()
  allBooks.forEach(book => map.set(book._id, book))
  selectedBooks.value = selectedBookIds.value.map(id => map.get(id)).filter(Boolean)
  bookSelectorVisible.value = false
}

// 移除已选书籍
const removeBook = (book) => {
  selectedBooks.value = selectedBooks.value.filter(b => b._id !== book._id)
}

// 提交表单
const handleSubmit = async () => {
  try {
    const formData = {
      ...promotionForm.value,
      bookIds: selectedBooks.value.map(book => book._id),
      startTime: promotionForm.value.timeRange[0],
      endTime: promotionForm.value.timeRange[1]
    }
    await app.callFunction({
      name: 'promotion',
      data: {
        action: dialogType.value === 'add' ? 'createPromotion' : 'updatePromotion',
        data: formData
      }
    })
    ElMessage.success('保存成功')
    dialogVisible.value = false
    getPromotionList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const handleBookPageChange = (page) => {
  pagination.currentPage = page
  getBookList(pagination.currentPage, pagination.pageSize)
}

const handleBookSizeChange = (size) => {
  pagination.pageSize = size
  getBookList(pagination.currentPage, pagination.pageSize)
}

onMounted(() => {
  getPromotionList()
})
</script>

<style scoped>
.promotion-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-books {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 